//
//  BMAMemoriExoViewController.m
//  Autismus
//
//  Created by Nicolas CHENG on 03/12/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "BMAMemoriExoViewController.h"
#import "BMAMemoriModel.h"
#import "BMAMovieViewController.h"

@interface BMAMemoriExoViewController ()

- (NSArray *)shuffleArray:(NSArray *)aArray;

- (void)updateImageButtons;

- (void)hideCardsForEmotion:(BMAEmotion)aEmotion;

- (void)unselectAll;

- (void)finish;

@end

/////////////////////////////////////////////////////////////////////////////////////////////

@implementation BMAMemoriExoViewController

@synthesize imageButton1;
@synthesize imageButton2;
@synthesize imageButton3;
@synthesize imageButton4;
@synthesize imageButton5;
@synthesize imageButton6;

- (id)initWithLevel:(NSUInteger)aLevel
{
    self = [super init];
    if (self != nil) 
    {
        level = -1;
        [self changeLevel:aLevel];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - IBActions

- (IBAction)imageButtonAction:(id)sender
{
    tapCount++;
    
    NSUInteger index = 0;
    
    UIButton *button = (UIButton *)sender;
    
    [button setImage:[[button imageForState:UIControlStateNormal] imageTintedWithColor:[UIColor blackColor] fraction:0.5] forState:UIControlStateNormal];
    
    if (sender == imageButton1)
    {
        index = 0;
    }
    else if (sender == imageButton2)
    {
        index = 1;
    }
    else if (sender == imageButton3)
    {
        index = 2;
    }
    else if (sender == imageButton4)
    {
        index = 3;
    }
    else if (sender == imageButton5)
    {
        index = 4;
    }
    else if (sender == imageButton6)
    {
        index = 5;
    }
    
    BMAMemoriModel *model = [memories objectAtIndex:index];

    if (tapCount == 2)
    {
        BOOL succeed = (model.emotion == lastEmotionTapped);
        
        if (succeed == YES)
        {
            emotionFoundCount++;
            [self hideCardsForEmotion:model.emotion];
        }
        else
        {
            [self unselectAll];
        }
        
        tapCount = 0;
    }
    
    lastEmotionTapped = model.emotion;
}

- (IBAction)goBack:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Private

- (NSArray *)shuffleArray:(NSArray *)aArray
{
	// create temporary autoreleased mutable array
	NSMutableArray *tmpArray = [NSMutableArray arrayWithCapacity:[aArray count]];
    
	for (id anObject in aArray)
	{
		NSUInteger randomPos = arc4random()%([tmpArray count]+1);
		[tmpArray insertObject:anObject atIndex:randomPos];
	}
    
	return [NSArray arrayWithArray:tmpArray];
}

- (void)updateImageButtons
{
    BMAMemoriModel *model = nil;
    
    model = [memories objectAtIndex:0];
    [imageButton1 setImage:[UIImage imageNamed:model.photoPath] forState:UIControlStateNormal];
    
    model = [memories objectAtIndex:1];
    [imageButton2 setImage:[UIImage imageNamed:model.photoPath] forState:UIControlStateNormal];
    
    model = [memories objectAtIndex:2];
    [imageButton3 setImage:[UIImage imageNamed:model.photoPath] forState:UIControlStateNormal];
    
    model = [memories objectAtIndex:3];
    [imageButton4 setImage:[UIImage imageNamed:model.photoPath] forState:UIControlStateNormal];
    
    model = [memories objectAtIndex:4];
    [imageButton5 setImage:[UIImage imageNamed:model.photoPath] forState:UIControlStateNormal];
    
    model = [memories objectAtIndex:5];
    [imageButton6 setImage:[UIImage imageNamed:model.photoPath] forState:UIControlStateNormal];
}

- (void)hideCardsForEmotion:(BMAEmotion)aEmotion
{
    BMAMemoriModel *model = nil;
    
    UIButton *button1 = nil;
    UIButton *button2 = nil;
    
    for (NSUInteger i = 0; i < 6; i++)
    {
        model = [memories objectAtIndex:i];
        
        if (model.emotion == aEmotion)
        {
            if (button1 == nil)
            {
                button1 = (UIButton *)[self.view viewWithTag:(100 + i)];
            }
            else
            {
                button2 = (UIButton *)[self.view viewWithTag:(100 + i)];
                break;
            }
        }
    }
    
    button1.userInteractionEnabled = NO;
    button2.userInteractionEnabled = NO;
    [UIView animateWithDuration:0.5 animations:^{
        button1.alpha = 0;
        button2.alpha = 0;
        
        CGRect rect = button1.frame;
        
        rect.origin.x += rect.size.width / 4;
        rect.origin.y += rect.size.height / 4;
        rect.size.width /= 2;
        rect.size.height /= 2;
        
        button1.frame = rect;
        
        rect = button2.frame;
        
        rect.origin.x += rect.size.width / 4;
        rect.origin.y += rect.size.height / 4;
        rect.size.width /= 2;
        rect.size.height /= 2;
        
        button2.frame = rect;
        
    } completion:^(BOOL finished) {
        button1.userInteractionEnabled = YES;
        button2.userInteractionEnabled = YES;
        
        if (emotionFoundCount == 3)
        {
            [self finish];
        }
    }];
}

- (void)unselectAll
{
    NSUInteger i = 0;
    
    UIButton *button = nil;
    
    for (i = 0; i < 6; i++)
    {
        button = (UIButton *)[self.view viewWithTag:(100 + i)];
        
        BMAMemoriModel *model = [memories objectAtIndex:i];
        [button setImage:[UIImage imageNamed:model.photoPath] forState:UIControlStateNormal];
    }
}

- (void)finish
{
    BMAMovieViewController* theMoviePlayer = [[BMAMovieViewController alloc] initWithPath:[[NSBundle mainBundle] pathForResource:@"win" ofType:@"mp4"]];
    
    [self presentModalViewController:theMoviePlayer animated:NO];
    [self.navigationController popViewControllerAnimated:NO];
}

#pragma mark - Public

- (void)changeLevel:(NSUInteger)aValue
{
    if (aValue == level)
    {
        return;
    }
    
    level = aValue;
    
    // x vignettes = x/2 emotions par page
    NSUInteger cardCount = 6;
    
    BMAAppManager *sharedManager = [BMAAppManager sharedInstance];
    
    NSUInteger emotionCount = [[sharedManager emotions] count];
    
    NSMutableArray *emotions = [NSMutableArray arrayWithCapacity:0];
    
    while ([emotions count] < (cardCount / 2))
    {
        BMAEmotion emotion = RAND_INT_VAL(0, emotionCount - 1);
        
        if ([emotions containsObject:[NSNumber numberWithInt:emotion]] == NO)
        {
            [emotions addObject:[NSNumber numberWithInt:emotion]];
        }
    }

    NSMutableArray *newMemories = [[NSMutableArray alloc] initWithCapacity:0];
    
    NSUInteger index = 0;
    
    for (index = 0; index < [emotions count]; index++)
    {
        BMAEmotion emotion = [[emotions objectAtIndex:index] intValue];
        
        BMAMemoriModel *model = [[BMAMemoriModel alloc] init];
        model.emotion = emotion;
        model.photoPath = [sharedManager randomPhotoPathFor:emotion];
            
        [newMemories addObject:model];
        
        // trouver les mêmes visages aux mêmes émotions
        if (level == 0)
        {
            [newMemories addObject:[model clone]];
        }
        // trouver les mêmes émotions sur des visages différents
        else if (level == 1)
        {
            NSString *newPath = model.photoPath;
            
            while ([newPath isEqualToString:model.photoPath] == YES)
            {
                newPath = [sharedManager randomPhotoPathFor:emotion];
            }
            
            model = [[BMAMemoriModel alloc] init];
            model.emotion = emotion;
            model.photoPath = newPath;
            
            [newMemories addObject:model];
        }
    }
    
    memories = [self shuffleArray:newMemories];
    DLOG(@"memories pour level %i = %@", level, memories);
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    level = 0;          // = niveau 1
    tapCount = 0;
    lastEmotionTapped = BMAEmotionJoyeux;
    emotionFoundCount = 0;
    
    [self updateImageButtons];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    self.imageButton1 = nil;
    self.imageButton2 = nil;
    self.imageButton3 = nil;
    self.imageButton4 = nil;
    self.imageButton5 = nil;
    self.imageButton6 = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
	return UIInterfaceOrientationIsLandscape(interfaceOrientation);
}

@end
